/*
 * Copyright (C) 2012 Rothens
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package rpg.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.logging.Level;

/**
 * rothens.tarhely.biz
 * @author k-zed
 */
public class LineReader implements Iterator<String>
{
	private BufferedReader br = null;
	private String nextLine = null;
	private String path = null;

	private String loadLine() throws IOException
	{
		nextLine = null;

		for(;;) {
			String l = br.readLine();
			if(l == null) {
				br.close();
				br = null;
				return l;
			}

			l = l.trim();
			if(l.length() == 0)
				continue;
			if(l.charAt(0) == '#')
				continue;
			nextLine = l;
			return l;
		}
	}

	public LineReader(String path)
	{
		this.path = path;

		try {
			br = new BufferedReader(new FileReader(path));
		} catch(IOException ex) {
			System.err.println("[LineReader] Exception while reading file " + path);
			br = null;
		}
	}

	public boolean hasNext()
	{
		if(br == null)
			return false;

		try {
			if(nextLine == null)
				loadLine();
		} catch(IOException ex) {
			System.err.println("[LineReader] Exception");
			br = null;
			nextLine = null;
			return false;
		}

		return nextLine != null;
	}

	public String next()
	{
		if(br == null)
			throw new NoSuchElementException();

		try {
			if(nextLine == null)
				loadLine();
		} catch(IOException ex) {
			System.err.println("[LineReader] Exception while reading file " + path);
			br = null;
			nextLine = null;
			throw new NoSuchElementException();
		}

		if(nextLine == null)
			throw new NoSuchElementException();

		String line = nextLine;
		nextLine = null;
		return line;
	}

	public void remove()
	{
		throw new UnsupportedOperationException();
	}
}
